<template>
  <div class="va-df-info-image">
    <a class="va-df-info-image-item" v-for="(img, idx) in imgs" :key="idx" :href="img" target="_blank"
       :style="[{backgroundImage: useImgTag ? null : `url(${encode(img)})`}, useImgTag ? {width: 'auto', height: 'auto'} : null]">
      <img v-if="useImgTag" :src="encode(img)" :style="{width: imgWidth, height: imgHeight}">
    </a>
  </div>
</template>

<script>
  import _ from 'lodash'

  export default {
    props: {
      value: {},
      field: Object,
      disabled: Boolean
    },
    data () {
      return {
        imgs: []
      }
    },
    computed: {
      useImgTag () {
        return this.field && !!this.field.useImgTag
      },
      imgWidth () {
        return this.field.imageWidth || (this.field.imageHeight ? 'auto' : null)
      },
      imgHeight () {
        return this.field.imageHeight || (this.field.imageWidth ? 'auto' : null)
      }
    },
    mounted () {
      this.updateImgs()
    },
    methods: {
      encode (url) {
        return encodeURI(url)
      },
      updateImgs () {
        if (this.field.infoRenderer) {
          let rst = this.field.infoRenderer(this.value)
          if (rst && rst.then) {
            rst.then(data => {
              this.imgs = data
            })
          } else {
            this.imgs = rst
          }
        } else {
          if (this.value) {
            if (_.isString(this.value) && this.value.indexOf(',') > -1) {
              this.value = _.filter(_.split(this.value, ','), e => !!e)
            }
            this.imgs = _.isArray(this.value) ? this.value : [this.value]
          } else {
            this.imgs = []
          }
        }
      }
    },
    watch: {
      value () {
        this.updateImgs()
      }
    }
  }
</script>
